package main

import "math"

var hash = map[int32]int{
	32: 1,  //空白
	43: 1,  //+号
	45: -1, //-号
	48: 0,
	49: 1,
	50: 2,
	51: 3,
	52: 4,
	53: 5,
	54: 6,
	55: 7,
	56: 8,
	57: 9,
}

func myAtoi(s string) int {
	rel := result{
		value:  0,
		symbol: 1,
		level:  0,
		count:  0,
		finish: false}

	for _, v := range s {
		if rel.Add(v) {
			break
		}
	}
	return rel.Value()
}

type result struct {
	value  int
	symbol int
	level  int //0:未开始,1:空白,2:+-号,3:数字
	count  int
	finish bool //结束
}

func (r *result) Add(v int32) bool {
	switch v {
	case 32:
		r.level0() //空白
	case 43, 45:
		r.level1(v) //+-号
	case 48, 49, 50, 51, 52, 53, 54, 55, 56, 57:
		r.level2(v) //数字
	default:
		r.finish = true
	}
	return r.finish
}

// level0 处理空白
func (r *result) level0() {
	//如果等级大于1，设置停止标记
	if r.level > 1 {
		r.finish = true
		return
	}
	r.level = 1
}

// level1 处理+-
func (r *result) level1(v int32) {
	if r.level > 2 {
		r.finish = true
		return
	}
	if v == 45 {
		r.symbol = -1
	}
	r.level = 3
}

// level2 处理数字
func (r *result) level2(v int32) {
	r.level = 3
	r.value = r.value*10 + hash[v]
	if r.value != 0 {
		r.count++
	}
	if r.outSize() {
		r.finish = true
		return
	}
}

// outSize 判断是否符合
func (r *result) outSize() bool {
	if r.count > 10 {
		if r.symbol == -1 {
			r.value = math.MinInt32
		} else {
			r.value = math.MaxInt32
		}
		return true
	}
	if r.symbol == -1 {
		if r.value*-1 < math.MinInt32 {
			r.value = math.MinInt32
			return true
		}
	} else {
		if r.value > math.MaxInt32 {
			r.value = math.MaxInt32
			return true
		}
	}
	return false
}

// Value 最终的值
func (r *result) Value() int {
	if r.value > 0 {
		r.value *= r.symbol
	}
	return r.value
}
